package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    UserService userService;
    @Autowired
    OrderDetailService orderDetailService;


    @Override
    @Transactional
    public void sunbmit(Orders orders) {
        //数据准备
        Long currentId = BaseContext.getCurrentId();//此用户id为用户id
        //1.1购物车数据
        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(sclqw);
        if (shoppingCartList==null||shoppingCartList.size()==0){
            throw new CustomException("购物车为空");
        }
        //1.2地址薄数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("地址为空");
        }
        //1.3用户数据
        User user = userService.getById(currentId);
        if (user==null){
            throw new CustomException("用户为空");
        }
        //1.4封装为List<OrdersDetail>集合
        //利用雪花算法 随机算出id
        long orderId = IdWorker.getId();
        //总金额来接收
        AtomicInteger totalAmount = new AtomicInteger(0);

        List<OrderDetail> orderDetailList=shoppingCartList.stream().map(shoppingCart ->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //计算当前商品的小计
            BigDecimal amount = shoppingCart.getAmount();//单价
            Integer number = shoppingCart.getNumber();//数量
            //单价*数量
            BigDecimal multiply = amount.multiply(new BigDecimal(number));
            totalAmount.getAndAdd(multiply.intValue());//把小计累加到总金额上
            return orderDetail;
                }).collect(Collectors.toList());

        //1.5封装为Orders实体类
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setAmount(new BigDecimal(totalAmount.get()));
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(currentId);
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //2.保存数据到订单表
        save(orders);
        //3.保存数据(集合)到订单明细表
        orderDetailService.saveBatch(orderDetailList);
        //4.清空购物车
        shoppingCartService.remove(sclqw);



    }
}